/**
 * 本文件定义一些生成图片通用的方法
 */
import { drawTextWithEllipsis } from "./common";
// 绘制一个带边框的背景，一般用于图片的主要区域背景
export function drawBgBorder(context, x, y, bgwidth, bgheight, opts) {
  // 绘制主要区域的背景
  // 定义圆角矩形的参数
  const x22 = x;
  const y22 = y;
  const width = bgwidth;
  const height = bgheight;
  const radius = opts.radius || 10; // 圆角的大小
  const borderWidth = opts.borderWidth || 2; // 边框宽度
  const startColor = opts.startColor || "#fff"; // 背景色起始
  const centerColor1 = opts.centerColor1 || ""; // 背景色中间1
  const centerColor2 = opts.centerColor2 || ""; // 背景色中间2
  const endColor = opts.endColor || "#fff"; // 背景色结束
  const borderColor = opts.borderColor || "#eee"; // 边框宽度

  // 创建一个渐变
  const gradient = context.createLinearGradient(x22, y22, x22 + width, y22 + height);
  gradient.addColorStop(0, startColor); // 起始颜色
  if (centerColor1) {
    gradient.addColorStop(0.4, centerColor1); // 背景色中间1
  }
  if (centerColor2) {
    gradient.addColorStop(0.73, centerColor2); // 背景色中间1
  }


  gradient.addColorStop(1, endColor); // 结束颜色

  // 设置边框样式
  context.lineWidth = borderWidth;
  context.strokeStyle = borderColor; // 边框颜色

  // 开始绘制边框路径
  context.beginPath();
  context.moveTo(x22 + radius, y22);
  context.arcTo(x22 + width, y22, x22 + width, y22 + radius, radius);
  context.lineTo(x22 + width, y22 + height - radius);
  context.arcTo(
    x22 + width,
    y22 + height,
    x22 + width - radius,
    y22 + height,
    radius
  );
  context.lineTo(x22 + radius, y22 + height);
  context.arcTo(x22, y22 + height, x22, y22 + radius, radius);
  context.lineTo(x22, y22 + borderWidth); // 修正起始点以闭合路径（由于边框宽度）
  context.closePath();

  // 绘制边框
  context.stroke();

  // 填充内部区域（稍微调整以避免边框重叠）
  context.beginPath();
  context.moveTo(x22 + radius + borderWidth / 2, y22 + borderWidth / 2); // 偏移以匹配边框
  context.arcTo(
    x22 + width - borderWidth / 2,
    y22 + borderWidth / 2,
    x22 + width - borderWidth / 2,
    y22 + radius + borderWidth / 2,
    radius - borderWidth / 2
  );
  context.lineTo(
    x22 + width - borderWidth / 2,
    y22 + height - radius - borderWidth / 2
  );
  context.arcTo(
    x22 + width - borderWidth / 2,
    y22 + height - borderWidth / 2,
    x22 + width - radius - borderWidth / 2,
    y22 + height - borderWidth / 2,
    radius - borderWidth / 2
  );
  context.lineTo(
    x22 + radius + borderWidth / 2,
    y22 + height - borderWidth / 2
  );
  context.arcTo(
    x22 + borderWidth / 2,
    y22 + height - borderWidth / 2,
    x22 + borderWidth / 2,
    y22 + radius + borderWidth / 2,
    radius - borderWidth / 2
  );
  context.lineTo(x22 + borderWidth / 2, y22 + borderWidth / 2);
  context.closePath();

  // 设置填充样式为渐变
  context.fillStyle = gradient;

  // 填充内部区域
  context.fill();
}
// 加载图片
export function getURLBase64(url) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status === 200) {
        var blob = this.response;
        var fileReader = new FileReader();
        fileReader.onloadend = function (e) {
          var result = e.target.result;
          resolve(result);
        };
        fileReader.readAsDataURL(blob);
      }
    };
    xhr.onerror = function (err) {
      reject(err);
    };
    xhr.send();
  });
}

// 加载图片并创建图片实例 
export function getURLBase64Image(url) {
  // ////console.log("%c Line:105 🥤 加载图片并创建图片实例url", "color:#2eafb0", url);
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status === 200) {
        var blob = this.response;
        var fileReader = new FileReader();
        fileReader.onloadend = function (e) {
          if (e.target.result) {
            var result = e.target.result;
            const image = new Image();
            image.src = result;
            image.onload = () => {
              resolve(image);
            };
          } else {
            reject("图片地址错误");
          }
        };
        fileReader.readAsDataURL(blob);
      }else{
        reject()
      }
    };
    xhr.onerror = function (err) {
      reject(err);
    };
    xhr.send();
  });
}

// 批量加载图片新
export async function loadImages(list, length, sign) {
  return new Promise(async (resolve, reject) => {
    if (list.length == 0) {
      reject(false);
    } else {
      let num = length
        ? length > list.length
          ? list.length
          : length
        : list.length;
      let imgs = [];
      let signImg;

      for (let i = 0; i < list.length; i++) {
        let file = list[i];
        if (file.imgUrl) {
          // console.log("%c Line:163 🍕 file.sort", "color:#fca650", file);
          // console.log("%c Line:163 🍕 file.kz1", "color:#fca650", file.kz1);
          let kz1 = file.kz1||'';
          let lv = "";
          let kz2 = "";
          try {
            let image = await getURLBase64Image(file.imgUrl);
            // console.log("%c Line:169 🍑 image", "color:#42b983", image);
            if (typeof Number(file.kz1) === 'number' && isFinite(Number(file.kz1))) {
              lv = file.kz1;
            } else {
              if (file.kz1 && file.kz1.includes('http')) {
                kz1 = await getURLBase64Image(file.kz1);
              } else if (file.kz1 == 'S') {
                kz1 = await getURLBase64Image('https://imgage.maimaihao.com/makeImg/huoying/S.png');
              } else if (file.kz1 == 'A') {
                kz1 = await getURLBase64Image('https://imgage.maimaihao.com/makeImg/huoying/A.png');
              }
            }
            if (sign && (file.sort || file.sort == 0)) {
              signImg = await getURLBase64Image(
                "https://imgage.maimaihao.com/makeImg/skinSigns/sign" + file.sort + ".png"
              );
            }
            if (file.kz2) {
              kz2 = file.kz2
            }
            if (file.gameId == 12) {
              // 永劫无间
              if (file.kz1) {
                lv = file.kz1
              }
            }
            // console.log("%c Line:172 🍔 lv", "color:#2eafb0", lv);
            // 图片实例化成功后存起来
            imgs.push({
              image: image,
              name: file.fieldName,
              sort: file.sort,
              sign: signImg,
              kz1: kz1,
              lv: lv,
              kz2: kz2
            });
            if (imgs.length >= num) {
              return resolve(imgs);
            }
          } catch (err) {
            console.log("%c Line:81 🍰 err", "color:#33a5ff", err);
            // continue;
          }
        }
      }

      resolve(imgs);
    }
  });
}

// 绘制图片 绘制一个区域的多张图片  单页 可带边框 可带名称  可带标签  带标签时一定要加载好标签图片在imgs里面
export function drawImagesArea(context, imgs, options) {
  // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
  if (imgs && imgs.length) {
    ////console.log("%c Line:590 🍕 imgs", "color:#f5ce50", imgs);
    let i = 0;
    let line = 1;
    let startX = options.startX;
    let startY = options.startY;
    let hideTxt = options.hideTxt || false;
    let isSign = options.isSign || false;
    let stepY = options.stepY || 80;
    let stepX = options.stepX || 40;
    let txtLineHeight = options.txtLineHeight || 50;
    let borderImg = options.borderImg || "";
    let imgWidth = options.imgWidth1 || 222;
    let height = options.imgHeight || 300;
    let y = startY + height + txtLineHeight;
    let imgy = startY;
    let textColor = options.textColor || "#fff";
    imgs.forEach((item) => {
      if ((i + 1) % (options.rowNum + 1) == 0) {
        imgy = imgy + stepY + height + txtLineHeight;
        y = imgy + height + txtLineHeight;
        line++;
        i = 0;
      }
      // 保持宽高比
      // const originalWidth = item.image.naturalWidth;
      // const originalHeight = item.image.naturalHeight;
      // const targetWidth = imgWidth;
      // const targetHeight = targetWidth * (originalHeight / originalWidth);
      context.drawImage(
        item.image,
        startX + (imgWidth + stepX) * i,
        imgy,
        imgWidth,
        height
      );
      if (borderImg) {
        context.drawImage(
          borderImg,
          startX + (imgWidth + stepX) * i - 8,
          imgy - 8,
          imgWidth + 16,
          height + 16
        );
      }
      if (isSign && item.sign) {
        // 皮肤标签
        context.drawImage(
          item.sign,
          startX + (imgWidth + stepX) * i + imgWidth - 50,
          imgy,
          50,
          50
        );
      }
      if (item.kz1) {
        // 皮肤标签
        context.drawImage(
          item.kz1,
          startX + (imgWidth + stepX) * i + (imgWidth - 150) / 2,
          imgy + height - 80,
          150,
          60
        );
      }
      //  if(item.lv){
      //   context.fillText(item.lv, startX + (imgWidth + stepX) * i, imgy+20);
      // }
      if (!hideTxt) {
        if (item.name.includes('「')) {
          // 火影
          const name1 = item.name.split('「')[0]
          const name2 = '「' + item.name.split('「')[1]

          context.fillText(name1, 20 + startX + (imgWidth + stepX) * i, y);
          context.fillText(name2, startX + (imgWidth + stepX) * i, y + 40);
        } else {
          context.fillText(item.name, startX + (imgWidth + stepX) * i, y);
        }

      }
      i++;
    });
    return context;
  } else {
    return context;
  }
}

// 带皮肤背景图 绘制图片 绘制一个区域的多张图片  单页 可带名称  cf 和平
export function drawImagesAreaBg(context, imgs, options) {
  // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
  if (imgs && imgs.length) {
    let i = 0;
    let line = 1;
    let startX = options.startX;
    let startY = options.startY;
    let hideTxt = options.hideTxt || false;
    let defaultSkinbg = options.defaultSkinbg || false;
    let stepY = options.stepY || 80;
    let stepX = options.stepX || 40;
    let txtLineHeight = options.txtLineHeight || 50;
    let txtInside = options.txtInside || false;
    let imgWidth = options.imgWidth1 || 222;
    let height = options.imgHeight || 300;
    let bgImgs = options.bgImgs || [];
    let gameId = options.gameId || '';
    let isFull = options.isFull || '';
    let isJuese = options.isJuese || false;
    let y = startY + height + txtLineHeight / 2;
    if (txtInside) {
      y = startY + height;
    }
    let imgy = startY;
    imgs.forEach((item) => {
      if ((i + 1) % (options.rowNum + 1) == 0) {
        if (txtInside) {
          imgy = imgy + stepY + height;
          y = imgy + height;
        } else {
          imgy = imgy + stepY + height + txtLineHeight;
          y = imgy + height + txtLineHeight / 2;
        }

        line++;
        i = 0;
      }

      // 绘制背景图
      if (item.lv && bgImgs[item.lv - 1]) {
        context.fillStyle = "#fff";
        const bg = bgImgs[item.lv - 1];
        // console.log("%c Line:223 🌭 bg", "color:#f5ce50", bg);
        context.drawImage(
          bg,
          startX + (imgWidth + stepX) * i,
          imgy,
          imgWidth,
          height
        );
      } else {
        // https://imgage.maimaihao.com/makeImg/defaultSkinbg.png
        if (defaultSkinbg && gameId != 10 && gameId != 12) {
          if (txtInside) {
            context.fillStyle = "#333";
          } else {
            context.fillStyle = "#fff";
          }
          if (options.textColor) {
            context.fillStyle = options.textColor;
          }

          context.drawImage(
            defaultSkinbg,
            startX + (imgWidth + stepX) * i,
            imgy,
            imgWidth,
            height
          );
        }
      }

      // 保持宽高比
      // const originalWidth = item.image.naturalWidth;
      // const originalHeight = item.image.naturalHeight;
      // const targetWidth = imgWidth;
      // const targetHeight = targetWidth * (originalHeight / originalWidth);
      if(gameId==67){
        const bg = bgImgs[item.kz2 - 2];
        if(bg){
          context.drawImage(
            bg,
            startX + (imgWidth + stepX) * i,
            imgy,
            imgWidth,
            height
          );
        }
      }
      if (gameId == 10) {
        // 火影忍者 永劫无间  前景图  字在图片内部 白字
        context.fillStyle = "#fff";
        context.font = "bold 24px Adobe Ming Std";

        if (!hideTxt) {
          //主图
          // 绘制皮肤
          context.drawImage(
            item.image,
            startX + (imgWidth + stepX) * i,
            imgy,
            imgWidth,
            height
          );
          // 绘制边框
          context.drawImage(
            defaultSkinbg,
            startX + (imgWidth + stepX) * i,
            imgy,
            imgWidth,
            height
          );
          //主图  绘制文字  
          const name = item.name.length > 7 ? item.name.slice(0, 7) + '...' : item.name
          context.fillText(
            name,
            startX + (imgWidth + stepX) * i + 15,
            y - txtLineHeight
          );
          if (item.kz1) {
            // 忍者等级 A  S
            context.drawImage(
              item.kz1,
              startX + (imgWidth + stepX) * i + 120,
              imgy + 60,
              90,
              110
            );
          }
          if (item.kz2 && Number(item.kz2)) {
            // 星级
            const star = bgImgs[Number(item.kz2) - 1];
            try {
              context.drawImage(
                star,
                startX + (imgWidth + stepX) * i + 5,
                imgy + 5,
                40,
                100
              );
            } catch (error) {

            }
          }
        } else {
          // 详情图没有文字
          // 绘制背景
          context.drawImage(
            defaultSkinbg,
            startX + (imgWidth + stepX) * i,
            imgy,
            imgWidth,
            height
          );
          // 绘制皮肤
          context.drawImage(
            item.image,
            startX + (imgWidth + stepX) * i + 10,
            imgy + 10,
            imgWidth - 20,
            height - 20
          );
          if (item.kz1) {
            // 忍者等级 A  S
            context.drawImage(
              item.kz1,
              startX + (imgWidth + stepX) * i + 140,
              imgy + 120,
              125,
              150
            );
          }
          if (item.kz2 && Number(item.kz2)) {
            // 星级
            const star = bgImgs[Number(item.kz2) - 1];
            try {
              context.drawImage(
                star,
                startX + (imgWidth + stepX) * i + 5,
                imgy + 5,
                60,
                150
              );
            } catch (error) {

            }
          }
        }



      } else if (gameId == 12) {
        // 永劫无间
        // 绘制皮肤
        context.drawImage(
          item.image,
          startX + (imgWidth + stepX) * i,
          imgy,
          imgWidth,
          height
        );
        // 绘制边框
        if (item.lv) {
          const borderImg = bgImgs[item.lv - 1]
          context.drawImage(
            borderImg,
            startX + (imgWidth + stepX) * i,
            imgy,
            imgWidth,
            height
          );
        }

        //主图  绘制文字  
        const name = item.name.length > 5 ? item.name.slice(0, 5) + '...' : item.name
        context.fillText(
          name,
          startX + (imgWidth + stepX) * i + 15,
          y - txtLineHeight
        );
      } else {
        // 其他游戏
        if(isFull){
          context.drawImage(
            item.image,
            startX + (imgWidth + stepX) * i ,
            imgy,
            imgWidth,
            height
          );
        }else{
          if (txtInside) {
            context.drawImage(
              item.image,
              options.skinImgWidth ? startX + (imgWidth + stepX) * i + (imgWidth - options.skinImgWidth) / 2 : startX + (imgWidth + stepX) * i + 40,
              imgy,
              options.skinImgWidth ? options.skinImgWidth : imgWidth - 80,
              options.skinImgHeight ? options.skinImgHeight : height - 60
            );
          } else {
            context.drawImage(
              item.image,
              startX + (imgWidth + stepX) * i + 15,
              imgy + 15,
              options.skinImgWidth ? options.skinImgWidth : imgWidth - 30,
              options.skinImgHeight ? options.skinImgHeight : height - 30
            );
          }
        }
        
      }



      //  if(item.lv){
      //   context.fillText(item.lv, startX + (imgWidth + stepX) * i, imgy+20);
      // }
      if (!hideTxt && gameId != 10 && gameId != 12) {
        if (txtInside) {
          if (options.textWrap && item.name.length > 7) {
            const name1 = item.name.slice(0, 7)
            const name2 = item.name.slice(7, 14)
            context.fillText(
              name1,
              startX + (imgWidth + stepX) * i + 10,
              y - txtLineHeight
            );
            context.fillText(
              name2,
              startX + (imgWidth + stepX) * i + 10,
              y - txtLineHeight + 40
            );
          } else {
            let name = item.name
            // if(gameId==67){
            //   // 三角洲  超出14字截掉
            //   if(name.length>14){
            //     name = name.slice(0, 14)
            //   }
            // }
            // context.fillText(
            //   name,
            //   startX + (imgWidth + stepX) * i + 10,
            //   y - txtLineHeight
            // );
            drawTextWithEllipsis(context,name, startX + (imgWidth + stepX) * i + 10, y - txtLineHeight,imgWidth)
          }
        } else {
          let txt = item.name
          // CF 名称拼接数量
          if(gameId==6&&item.kz2){
            txt = `(${item.kz2})${txt}`
          }
          // context.fillText(
          //   txt,
          //   startX + (imgWidth + stepX) * i + 15,
          //   y + 13
          // );
          drawTextWithEllipsis(context,txt, startX + (imgWidth + stepX) * i + 15,y + 13,imgWidth)
        }
      }
      // 王者 右上角等级
      if (gameId == 2 && item.kz2) {
        context.fillStyle = "#333";
        context.fillText(
          item.kz2 + '级',
          startX + (imgWidth + stepX) * i + imgWidth - 50,
          imgy + 30
        );

      }
      i++;
    });
    return context;
  } else {
    return context;
  }
}


/**
 * 将图片转换为PNG格式
 * @param {File|Blob|string} image - 图片文件、Blob对象或图片URL
 * @param {number} [quality=1] - 图片质量（0-1），仅对某些格式有效
 * @returns {Promise<Blob>} 返回一个Promise，解析为PNG格式的Blob对象
 */
export async function convertImageToPNG(image, quality = 0.6) {
  try {
    // 1. 获取图片数据
    let imageData;
    if (typeof image === 'string') {
      // 如果是URL，先获取图片
      const response = await fetch(image);
      imageData = await response.blob();
    } else {
      imageData = image;
    }
    
    // 2. 创建图片元素并加载
    const img = new Image();
    const imgLoadPromise = new Promise((resolve, reject) => {
      img.onload = resolve;
      img.onerror = () => reject(new Error('图片加载失败'));
    });
    
    img.src = URL.createObjectURL(imageData);
    await imgLoadPromise;
    
    // 3. 创建canvas并绘制图片
    const canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth || img.width;
    canvas.height = img.naturalHeight || img.height;
    
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    
    // 4. 将canvas内容转换为PNG格式的Blob
    return new Promise((resolve) => {
      canvas.toBlob((blob) => {
        resolve(blob);
      }, 'image/png', quality);
    });
  } catch (error) {
    console.error('图片转换失败:', error);
    throw error;
  }
}